/*
 * Message.java
 *
 * Created on March 30, 2009, 4:43 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package org.vacuela.publish.desktop;


import com.u2d.app.PersistenceMechanism;
import com.u2d.list.RelationalList;
import com.u2d.model.AbstractComplexEObject;
import com.u2d.model.Title;
import com.u2d.type.atom.StringEO;
import com.u2d.type.atom.TextEO;
import java.util.*;
import com.u2d.type.atom.*;
import com.u2d.model.ComplexType;
import static org.vacuela.publish.constant.Constant.*;
import com.u2d.reflection.Fld;
import org.apache.commons.lang.StringUtils;
import com.u2d.element.Field;
/**
 *
 * @author nestor.carrasco
 */
public class Message extends AbstractComplexEObject {

    private TextEO texto = new TextEO();
    private StringEO numeros = new StringEO();
    private final RelationalList contactos = new RelationalList(Contact.class);
    public static Class contactosType = Contact.class;
    public static final int contactosRelationType = PersistenceMechanism.MANY_TO_MANY;
    //public static String contactosInverseFieldName = "message";

    private final RelationalList grupos = new RelationalList(MyGroup.class);
    public static Class gruposType = MyGroup.class;
    public static final int gruposRelationType = PersistenceMechanism.MANY_TO_MANY;
    //public static String gruposInverseFieldName = "message";
    private final StringEO status = new StringEO(NEW);
    private final StringEO priority = new StringEO(MEDIUM);
    public static String[] fieldOrder = {"numeros", "grupos", "contactos", "texto","totalChars","totalMsgs","msgType"};
     public static String[] hidden = {"msgStatus","msgPriority","msgCreatedDate","msgScheduledDate","msgSentDate"};
     public static String[] readOnly = {"totalChars","totalMsgs","msgType"};

     private final DateTime createdDate = new DateTime(new Date());
     private final DateTime scheduledDate = new DateTime();
     private final DateTime sentDate = new DateTime();
     private final IntEO totalChars = new IntEO(0);
     private final IntEO totalMsg = new IntEO(0);
     private final StringEO msgType = new StringEO(OUT_TYPE_MSG);


    /** Creates a new instance of Message */
    public Message() {
        this.texto.addChangeListener(new javax.swing.event.ChangeListener()
            {

               public void stateChanged(javax.swing.event.ChangeEvent evt)               {
                   String msgText = texto.stringValue();
                   int chars = 0;
                   int msgs = 0;

                   if ( msgText == null || msgText.trim().equals("")){
                        chars = msgs = 0;
                       // fireValidationException("The Text is Mandatory");
                         
                   }else{
                          chars = msgText.length();
                         if (chars > 0){
                             msgs = chars / 150;
                             msgs++;
                         }else{
                             // fireValidationException("The Text is Mandatory");
                         }
                   }
                        totalChars.setValue(chars);
                        totalMsg.setValue(msgs);
               }
            });
    }
    
      public int validate(){
            int count = super.validate();
            String phoneNumbers = this.numeros.stringValue();
            
            if ( null != phoneNumbers && !"".equals(phoneNumbers.trim())){
                String phones[] = StringUtils.split(phoneNumbers, PHONE_NUMBER_SEPARATOR);
                for (String num: phones){
                    if (null == num || num.length() != LEN_PHONE_NUMBER || !StringUtils.isNumeric(num)){
                        fireValidationException("Wrong Phone Numbers > " + phoneNumbers);
                        count++;
                    }
                }
            }
            if ( (phoneNumbers == null || "".equals(phoneNumbers)) &&
                 (contactos.getSize() == 0 ) &&
                    (grupos.getSize() == 0)){
                fireValidationException("To send a message is required a least a Number or a Group or a Contact");
                        count++;
            }
            return count;
   }
      
    public TextEO getTexto() {
        return texto;
    }

    @Fld(description = "More than one Number split with ;")
    public StringEO getNumeros() {
        return numeros;
    }

    public Title title() {
        int len = texto.toString().length();
        StringBuilder sb = null;
        if (len > 65) {
            sb = new StringBuilder(texto.toString().substring(0, 60));
            sb.append("...");
        } else {
            sb = new StringBuilder(texto.toString());
        }
        sb.append(" ::Status:: ").append(status);
        return new Title(sb.toString());
    }

    public RelationalList getContactos() {
        return contactos;
    }

    public RelationalList getGrupos() {
        return grupos;
    }

    public StringEO getMsgStatus(){
        return status;
    }

    public StringEO getMsgPriority(){
        return priority;
    }

    public DateTime getMsgCreatedDate(){
     return this.createdDate;
    }

    public DateTime getMsgScheduledDate(){
        return this.scheduledDate;
    }

    public DateTime getMsgSentDate(){
        return this.sentDate;
    }

   @Fld(persist = false)
    public IntEO getTotalChars(){
        return this.totalChars;
    }

   @Fld(persist = false)
    public IntEO getTotalMsgs(){
        return this.totalMsg;
    }
   
   public StringEO getMsgType(){
       return this.msgType;
   }
}
/*
  class MsgStatus extends ChoiceEO {

        public MsgStatus() {
        }

        public MsgStatus(String value) {
            setValue(value);
        }
        private static Set<String> STATUS_OPTIONS = new HashSet<String>();


        static {
            STATUS_OPTIONS.add(Constant.NEW);
            STATUS_OPTIONS.add(Constant.SCHEDULED);
            STATUS_OPTIONS.add(Constant.SENT);
        }

        public Collection entries() {
            return STATUS_OPTIONS;
        }
    }

    class MsgPriority extends ChoiceEO {

        public MsgPriority() {
        }

        public MsgPriority(String value) {
            setValue(value);
        }
        private static Set<String> STATUS_PRIORITY = new HashSet<String>();


        static {
            STATUS_PRIORITY.add(Constant.LOW);
            STATUS_PRIORITY.add(Constant.MEDIUM);
            STATUS_PRIORITY.add(Constant.HIGH);
        }

        public Collection entries() {
            return STATUS_PRIORITY;
        }
    }
    */
